import random
import datetime

# 初始化用户账户余额
money = 1000.0

# 商场商品列表（商品名称和价格）
goods = [
    {"name": "苹果", "price": 10, "category": "水果"},
    {"name": "空调", "price": 3000, "category": "家电"},
    {"name": "牛奶", "price": 20, "category": "饮品"},
    {"name": "书本", "price": 50, "category": "文具"},
    {"name": "手机", "price": 5000, "category": "电子产品"},
    {"name": "面包", "price": 15, "category": "食品"}
]

# 初始化空的购物车
shopping_cart = []

# 记录购物开始时间
start_time = datetime.datetime.now()

print("===== 欢迎进入购物系统 =====")
print(f"您的初始余额: {money}元")

# 1. 抽取优惠券
# 10张可能的优惠券（每张包含商品类别和折扣率）
coupons = [
    {"category": "家电", "discount_rate": 0.8},
    {"category": "电子产品", "discount_rate": 0.85},
    {"category": "饮品", "discount_rate": 0.9},
    {"category": "水果", "discount_rate": 0.7},
    {"category": "文具", "discount_rate": 0.95},
    {"category": "食品", "discount_rate": 0.85},
    {"category": "家电", "discount_rate": 0.75},
    {"category": "电子产品", "discount_rate": 0.8},
    {"category": "全部", "discount_rate": 0.9},  # 全场九折券
    {"category": "家电", "discount_rate": 0.6}  # 家电特别优惠券
]

selected_coupon = random.choice(coupons)
print("=" * 40)
if selected_coupon["category"] == "全部":
    print(f"🎉 恭喜您抽到全场通用券！可享受{selected_coupon['discount_rate'] * 10}折优惠！")
else:
    print(f"🎉 恭喜您抽到【{selected_coupon['category']}类商品】券！可享受{selected_coupon['discount_rate'] * 10}折优惠！")
print("=" * 40)

# 用于记录已使用优惠券状态
used_coupon = False

# 2. 购物主循环
print("可用商品:", [g["name"] for g in goods])
total_discount = 0.0  # 记录总优惠金额

while True:
    action = input("\n请选择操作: (A)添加商品/(R)退货/(Q)结算: ").strip().lower()

    # 结算退出
    if action == 'q':
        break

    # 退货功能
    if action == 'r':
        if not shopping_cart:
            print("购物车为空，无需退货！")
            continue

        print("\n当前购物车:")
        for idx, item in enumerate(shopping_cart, 1):
            print(f"{idx}. {item['name']} - {item['price']}元", end='')
            if 'pay_price' in item:
                print(f" (优惠价: {item['pay_price']:.2f}元)")
            else:
                print()

        try:
            choice = int(input("请输入要退货的商品序号: ")) - 1
            if 0 <= choice < len(shopping_cart):
                item = shopping_cart.pop(choice)

                # 退款金额（如果使用了优惠券，则退实际支付金额）
                refund = item['pay_price'] if 'pay_price' in item else item['price']
                money += refund

                # 如果使用了优惠券且是全场券，则更新优惠金额
                if used_coupon and selected_coupon["category"] == "全部" and 'pay_price' in item:
                    original_price = item['price']
                    discount = original_price - refund
                    total_discount -= discount

                print(f"✅ 已成功退货 {item['name']}! 退还金额: {refund:.2f}元")
                print(f"当前余额: {money:.2f}元")
            else:
                print("⚠️ 无效的商品序号！")
        except ValueError:
            print("⚠️ 请输入有效的数字序号！")
        continue

    # 添加商品
    if action == 'a':
        item_name = input("请输入要购买的商品名称: ").strip()

        # 检查商品是否存在
        found_item = None
        for product in goods:
            if product["name"] == item_name:
                found_item = product
                break

        # 商品不存在的情况
        if not found_item:
            print("提示：没有这个商品，请选择其他商品！")
            continue

        # 计算实际价格（考虑优惠券）
        if (selected_coupon["category"] == found_item["category"] or
            selected_coupon["category"] == "全部") and not used_coupon:

            # 应用优惠券
            discount_rate = selected_coupon["discount_rate"]
            actual_price = found_item["price"] * discount_rate

            # 标记优惠券已使用（如果是全场券则不标记，可使用多次）
            if selected_coupon["category"] != "全部":
                used_coupon = True

            # 记录优惠金额
            discount = found_item["price"] - actual_price
            total_discount += discount

            print(f"🎉 优惠券生效！{found_item['name']}从{found_item['price']}元优惠到{actual_price:.2f}元")
        else:
            actual_price = found_item["price"]

        # 检查余额是否足够
        if money >= actual_price:
            # 添加到购物车，记录实际支付价格
            cart_item = found_item.copy()
            cart_item["pay_price"] = actual_price
            shopping_cart.append(cart_item)

            # 扣减余额
            money -= actual_price
            print(f"✅ 成功添加 {found_item['name']} 到购物车！")
            if actual_price != found_item["price"]:
                print(f"  优惠价: {actual_price:.2f}元 (原价: {found_item['price']}元)")
            print(f"  当前余额: {money:.2f}元")
        else:
            need_money = actual_price - money
            print(f"⚠️ 余额不足！商品需要 {actual_price:.2f}元，还差{need_money:.2f}元")
    else:
        print("⚠️ 无效的操作，请重新输入！")

# 3. 打印优化后的购物小票
end_time = datetime.datetime.now()
print("\n" + "=" * 50)
print(" " * 15 + "💳 购物小票")
print("=" * 50)
print(f"购物时间: {start_time.strftime('%Y-%m-%d %H:%M')} - {end_time.strftime('%H:%M')}")
print(f"购物时长: {(end_time - start_time).seconds // 60}分钟")
print("-" * 50)
print(f"{'商品名称':<10}{'原价':>10}{'实付':>10}")
print("-" * 50)

total_original = 0
total_paid = 0

for item in shopping_cart:
    name = item["name"]
    original = item["price"]
    paid = item["pay_price"]

    print(f"{name:<10}{original:>10.2f}元{paid:>10.2f}元")

    total_original += original
    total_paid += paid

print("-" * 50)
print(f"{'商品总数:':<10}{len(shopping_cart):>12}件")
print(f"{'商品总额:':<10}{total_original:>12.2f}元")

if total_discount > 0:
    print(f"{'优惠金额:':<10}{total_discount:>12.2f}元")

print(f"{'实付金额:':<10}{total_paid:>12.2f}元")
print(f"{'账户余额:':<10}{money:>12.2f}元")
print("=" * 50)
print("感谢您的光临！欢迎下次再来！")